<template>
  <div class="store-dashboard">
    <!-- 顶部门店选择 -->
    <el-card class="store-selector-card">
      <el-form :inline="true">
        <el-form-item label="选择门店">
          <el-select v-model="selectedStoreId" placeholder="请选择门店" @change="handleStoreChange">
            <el-option
              v-for="store in storeList"
              :key="store.id"
              :label="store.name"
              :value="store.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRefresh">刷新数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 核心指标卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <el-icon :size="32"><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">今日销售额</div>
            <div class="stat-value">¥{{ todaySales.toLocaleString() }}</div>
            <div class="stat-trend">
              <el-icon class="trend-icon up"><CaretTop /></el-icon>
              <span class="trend-text up">较昨日 +15.8%</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
            <el-icon :size="32"><ShoppingCart /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">今日订单数</div>
            <div class="stat-value">{{ todayOrders }}</div>
            <div class="stat-trend">
              <el-icon class="trend-icon up"><CaretTop /></el-icon>
              <span class="trend-text up">较昨日 +8.5%</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
            <el-icon :size="32"><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">今日客流量</div>
            <div class="stat-value">{{ todayVisitors }}</div>
            <div class="stat-trend">
              <el-icon class="trend-icon down"><CaretBottom /></el-icon>
              <span class="trend-text down">较昨日 -3.2%</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
            <el-icon :size="32"><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">客单价</div>
            <div class="stat-value">¥{{ avgOrderValue }}</div>
            <div class="stat-trend">
              <el-icon class="trend-icon up"><CaretTop /></el-icon>
              <span class="trend-text up">较昨日 +12.3%</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 销售趋势图 -->
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span class="chart-title">📈 销售趋势分析</span>
              <el-radio-group v-model="salesChartType" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="salesChartRef"></div>
        </el-card>
      </el-col>

      <!-- 商品销售排行 -->
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span class="chart-title">🏆 商品销售排行 TOP10</span>
            </div>
          </template>
          <div class="ranking-list">
            <div
              v-for="(item, index) in topProducts"
              :key="item.id"
              class="ranking-item"
            >
              <div class="ranking-index" :class="getRankClass(index)">
                {{ index + 1 }}
              </div>
              <div class="ranking-content">
                <div class="ranking-name">{{ item.name }}</div>
                <div class="ranking-info">
                  <span>销量: {{ item.sales }}</span>
                  <span class="ranking-amount">¥{{ item.amount.toLocaleString() }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行图表 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 客流分析 -->
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <span class="chart-title">👥 客流分时分析</span>
          </template>
          <div class="chart-container" ref="trafficChartRef"></div>
        </el-card>
      </el-col>

      <!-- 支付方式分析 -->
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <span class="chart-title">💳 支付方式占比</span>
          </template>
          <div class="chart-container" ref="paymentChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 门店员工业绩 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span class="chart-title">👨‍💼 员工业绩排行</span>
          </template>
          <el-table :data="staffPerformance" border stripe>
            <el-table-column type="index" label="排名" width="70" align="center" />
            <el-table-column prop="name" label="员工姓名" width="120" />
            <el-table-column prop="position" label="职位" width="100" />
            <el-table-column prop="orderCount" label="成交订单" width="100" align="center">
              <template #default="{ row }">
                <el-tag type="success">{{ row.orderCount }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sales" label="销售额" width="150" align="right">
              <template #default="{ row }">
                <span class="sales-amount">¥{{ row.sales.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="customerCount" label="服务客户数" width="120" align="center" />
            <el-table-column prop="avgOrderValue" label="客单价" width="120" align="right">
              <template #default="{ row }">
                ¥{{ row.avgOrderValue }}
              </template>
            </el-table-column>
            <el-table-column prop="refundRate" label="退款率" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.refundRate < 5 ? 'success' : 'warning'">
                  {{ row.refundRate }}%
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="satisfaction" label="满意度" width="100" align="center">
              <template #default="{ row }">
                <el-rate v-model="row.satisfaction" disabled show-score text-color="#ff9900" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleViewStaffDetail(row)">查看详情</el-button>
                <el-button link type="success" @click="handleReward(row)">奖励</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时动态 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="chart-header">
              <span class="chart-title">📢 门店实时动态</span>
              <el-button size="small" @click="handleRefreshActivities">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="activity in activities"
              :key="activity.id"
              :timestamp="activity.time"
              :type="activity.type"
            >
              <div class="activity-content">
                <span class="activity-icon">{{ activity.icon }}</span>
                <span>{{ activity.content }}</span>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  TrendCharts, ShoppingCart, User, Money, CaretTop, CaretBottom, Refresh
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const route = useRoute()

// 门店列表
const storeList = ref([
  { id: 1, name: '深圳旗舰店' },
  { id: 2, name: '上海陆家嘴店' },
  { id: 3, name: '北京国贸店' },
  { id: 4, name: '广州天河店' },
  { id: 5, name: '成都春熙路店' }
])

// 选中的门店
const selectedStoreId = ref(route.query.storeId ? parseInt(route.query.storeId) : 1)

// 日期范围
const dateRange = ref([])

// 销售图表类型
const salesChartType = ref('day')

// 核心指标
const todaySales = ref(156789)
const todayOrders = ref(328)
const todayVisitors = ref(1245)
const avgOrderValue = ref(478)

// 商品销售排行
const topProducts = ref([
  { id: 1, name: 'iPhone 15 Pro Max', sales: 156, amount: 1456780 },
  { id: 2, name: 'MacBook Pro 16"', sales: 89, amount: 1234560 },
  { id: 3, name: 'iPad Air', sales: 234, amount: 987650 },
  { id: 4, name: 'AirPods Pro', sales: 456, amount: 876540 },
  { id: 5, name: 'Apple Watch Ultra', sales: 178, amount: 765430 },
  { id: 6, name: 'Mac Studio', sales: 45, amount: 654320 },
  { id: 7, name: 'HomePod', sales: 234, amount: 543210 },
  { id: 8, name: 'Magic Keyboard', sales: 345, amount: 432100 },
  { id: 9, name: 'AirTag', sales: 678, amount: 321000 },
  { id: 10, name: 'MagSafe充电器', sales: 890, amount: 210000 }
])

// 员工业绩
const staffPerformance = ref([
  {
    id: 1,
    name: '张伟',
    position: '销售顾问',
    orderCount: 89,
    sales: 456789,
    customerCount: 145,
    avgOrderValue: 5132,
    refundRate: 2.3,
    satisfaction: 4.8
  },
  {
    id: 2,
    name: '李芳',
    position: '销售顾问',
    orderCount: 76,
    sales: 398765,
    customerCount: 128,
    avgOrderValue: 5247,
    refundRate: 1.8,
    satisfaction: 4.9
  },
  {
    id: 3,
    name: '王强',
    position: '高级顾问',
    orderCount: 92,
    sales: 512345,
    customerCount: 156,
    avgOrderValue: 5569,
    refundRate: 3.1,
    satisfaction: 4.7
  },
  {
    id: 4,
    name: '陈敏',
    position: '销售顾问',
    orderCount: 65,
    sales: 287654,
    customerCount: 98,
    avgOrderValue: 4425,
    refundRate: 2.9,
    satisfaction: 4.6
  },
  {
    id: 5,
    name: '刘洋',
    position: '销售顾问',
    orderCount: 58,
    sales: 245678,
    customerCount: 87,
    avgOrderValue: 4236,
    refundRate: 4.2,
    satisfaction: 4.5
  }
])

// 实时动态
const activities = ref([
  { id: 1, time: '15:32:18', type: 'success', icon: '💰', content: '张伟完成了一笔￥15,999的订单' },
  { id: 2, time: '15:28:45', type: 'primary', icon: '👤', content: '新增会员：李明（手机号：138****5678）' },
  { id: 3, time: '15:25:12', type: 'success', icon: '💰', content: '李芳完成了一笔￥8,599的订单' },
  { id: 4, time: '15:20:33', type: 'warning', icon: '⚠️', content: 'iPhone 15 Pro库存预警（剩余5台）' },
  { id: 5, time: '15:15:08', type: 'success', icon: '💰', content: '王强完成了一笔￥23,998的订单' },
  { id: 6, time: '15:10:45', type: 'info', icon: '📦', content: '收到配送中心发货：订单号 SO202401001' },
  { id: 7, time: '15:05:22', type: 'primary', icon: '👤', content: '新增会员：王芳（手机号：139****1234）' },
  { id: 8, time: '15:00:00', type: 'danger', icon: '🔔', content: '下午茶时间到，员工轮休开始' }
])

// 图表引用
const salesChartRef = ref(null)
const trafficChartRef = ref(null)
const paymentChartRef = ref(null)

// 门店变更
const handleStoreChange = () => {
  ElMessage.success('切换门店成功，正在加载数据')
  handleRefresh()
}

// 日期变更
const handleDateChange = () => {
  handleRefresh()
}

// 刷新数据
const handleRefresh = () => {
  ElMessage.success('数据刷新成功')
  // 这里可以调用API刷新数据
}

// 刷新动态
const handleRefreshActivities = () => {
  ElMessage.success('动态刷新成功')
}

// 查看员工详情
const handleViewStaffDetail = (row) => {
  ElMessage.info(`查看员工 ${row.name} 的详细信息`)
}

// 奖励员工
const handleReward = (row) => {
  ElMessage.success(`已向员工 ${row.name} 发放奖励`)
}

// 获取排名样式
const getRankClass = (index) => {
  if (index === 0) return 'rank-first'
  if (index === 1) return 'rank-second'
  if (index === 2) return 'rank-third'
  return ''
}

// 初始化销售趋势图
const initSalesChart = () => {
  const chart = echarts.init(salesChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['销售额', '订单量']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(元)',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '订单量',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        data: [120000, 132000, 101000, 134000, 90000, 230000, 210000],
        smooth: true,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '订单量',
        type: 'bar',
        yAxisIndex: 1,
        data: [256, 289, 198, 278, 187, 478, 445],
        itemStyle: { color: '#67c23a' }
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化客流分析图
const initTrafficChart = () => {
  const chart = echarts.init(trafficChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00']
    },
    yAxis: {
      type: 'value',
      name: '客流量'
    },
    series: [
      {
        name: '客流量',
        type: 'line',
        data: [45, 78, 123, 156, 98, 134, 189, 234, 267, 298, 245, 178],
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        },
        itemStyle: { color: '#409eff' }
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化支付方式图
const initPaymentChart = () => {
  const chart = echarts.init(paymentChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      bottom: 10,
      left: 'center'
    },
    series: [
      {
        name: '支付方式',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 45, name: '微信支付', itemStyle: { color: '#67c23a' } },
          { value: 30, name: '支付宝', itemStyle: { color: '#409eff' } },
          { value: 15, name: '现金', itemStyle: { color: '#e6a23c' } },
          { value: 8, name: '银行卡', itemStyle: { color: '#909399' } },
          { value: 2, name: '其他', itemStyle: { color: '#f56c6c' } }
        ]
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initSalesChart()
    initTrafficChart()
    initPaymentChart()
  })
})
</script>

<style scoped>
.store-dashboard {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.store-selector-card {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
  margin-bottom: 20px;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.trend-icon {
  margin-right: 3px;
}

.trend-icon.up {
  color: #67c23a;
}

.trend-icon.down {
  color: #f56c6c;
}

.trend-text.up {
  color: #67c23a;
}

.trend-text.down {
  color: #f56c6c;
}

/* 图表区域 */
.chart-row {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
}

.chart-container {
  width: 100%;
  height: 300px;
}

/* 排行榜列表 */
.ranking-list {
  max-height: 300px;
  overflow-y: auto;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  transition: background 0.3s;
}

.ranking-item:hover {
  background: #f5f7fa;
}

.ranking-index {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  background: #909399;
  color: white;
  margin-right: 12px;
  flex-shrink: 0;
}

.ranking-index.rank-first {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  font-size: 16px;
}

.ranking-index.rank-second {
  background: linear-gradient(135deg, #c0c0c0 0%, #e8e8e8 100%);
}

.ranking-index.rank-third {
  background: linear-gradient(135deg, #cd7f32 0%, #d4a574 100%);
}

.ranking-content {
  flex: 1;
}

.ranking-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
}

.ranking-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.ranking-amount {
  color: #f56c6c;
  font-weight: bold;
}

/* 员工业绩 */
.sales-amount {
  color: #f56c6c;
  font-weight: bold;
}

/* 实时动态 */
.activity-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.activity-icon {
  font-size: 16px;
}
</style>

